<?php
class Sale_lib
{
	var $CI;

  	function __construct()
	{
		$this->CI =& get_instance();
	}

	function get_cart()
	{
		if(!$this->CI->session->userdata('cart'))
			$this->set_cart(array());

		return $this->CI->session->userdata('cart');
	}

	function set_cart($cart_data)
	{
		$this->CI->session->set_userdata('cart',$cart_data);
	}

	//Alain Multiple Payments
	function get_payments()
	{
		if( !$this->CI->session->userdata( 'payments' ) )
			$this->set_payments( array( ) );

		return $this->CI->session->userdata('payments');
	}

	//Alain Multiple Payments
	function set_payments($payments_data)
	{
		$this->CI->session->set_userdata('payments',$payments_data);
	}
	
	function add_payment_copy( $payment_id, $payment_amount )
	{
		$payments = $this->get_payments();
		$payment = array( $payment_id=>
				array(
						'payment_type' => $payment_id,
						'payment_amount' => $payment_amount
				)
		);
	
		//payment_method already exists, add to payment_amount
		if( isset( $payments[$payment_id] ) )
		{
			$payments[$payment_id]['payment_amount'] += $payment_amount;
		}
		else
		{
			//add to existing array
			$payments += $payment;
		}
	
		$this->set_payments( $payments );
		return true;
	
	}

	function add_payment( $payment_id, $payment_amount )
	{	
		if ($payment_amount <= 0) return false;
		
		if ($payment_id == 'Point') {
			$customer_id=$this->get_customer();
			if($customer_id!=-1)
			{
				$info=$this->CI->Customer->get_info($customer_id);
				$current_point = $info->point;
				$base_rate = $this->CI->Appconfig->get('convert_rate');
				if ($payment_amount <= $current_point) {
					$payment_amount *= $base_rate;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
		
		$payments = $this->get_payments();
		$payment = array( $payment_id=>
		array(
			'payment_type' => $payment_id,
			'payment_amount' => $payment_amount
			)
		);

		//payment_method already exists, add to payment_amount
		if( isset( $payments[$payment_id] ) )
		{
			$payments[$payment_id]['payment_amount'] = $payment_amount;
		}
		else
		{
			//add to existing array
			$payments += $payment;
		}

		$this->set_payments( $payments );
		return true;

	}

	//Alain Multiple Payments
	function edit_payment($payment_id,$payment_amount)
	{
		$payments = $this->get_payments();
		if(isset($payments[$payment_id]))
		{
			$this->delete_payment($payment_id);
			$this->add_payment($payment_id, $payment_amount);
			//$payments[$payment_id]['payment_type'] = $payment_id;
			//$payments[$payment_id]['payment_amount'] = $payment_amount;
			//$this->set_payments($payment_id);
		}

		return false;
	}

	//Alain Multiple Payments
	function delete_payment( $payment_id )
	{
		$payments = $this->get_payments();
		unset( $payments[urldecode( $payment_id )] );
		$this->set_payments( $payments );
	}

	//Alain Multiple Payments
	function empty_payments()
	{
		$this->CI->session->unset_userdata('payments');
	}

	//Alain Multiple Payments
	function get_payments_total()
	{
		$subtotal = 0;
		foreach($this->get_payments() as $payments)
		{
		    $subtotal+=$payments['payment_amount'];
		}
		return $subtotal;
	}

	//Alain Multiple Payments
	function get_amount_due()
	{
		$amount_due=0;
		$payment_total = $this->get_payments_total();
		$sales_total=$this->get_total();
		$amount_due=to_currency_no_money($sales_total - $payment_total);
		return $amount_due;
	}

	function get_customer()
	{
		if(!$this->CI->session->userdata('customer'))
			$this->set_customer(-1);

		return $this->CI->session->userdata('customer');
	}

	function set_customer($customer_id)
	{
		$this->CI->session->set_userdata('customer',$customer_id);
	}
    
	function add_item($item_id,$quantity=1,$price=null)
	{
		//make sure item exists	     
		if($this->validate_item($item_id) == false)
        {
            return false;
        }

		//Alain Serialization and Description

		//Get all items in the cart so far...
		$items = $this->get_cart();

        //We need to loop through all items in the cart.
        //If the item is already there, get it's key($updatekey).
        //We also need to get the next key that we are going to use in case we need to add the
        //item to the cart. Since items can be deleted, we can't use a count. we use the highest key + 1.

        $maxkey=0;                       //Highest key so far
        $itemalreadyinsale=FALSE;        //We did not find the item yet.
		$insertkey=0;                    //Key to use for new entry.
		$updatekey=0;                    //Key to use to update(quantity)

		foreach ($items as $item)
		{
            //We primed the loop so maxkey is 0 the first time.
            //Also, we have stored the key in the element itself so we can compare.

			if($maxkey <= $item['line'])
			{
				$maxkey = $item['line'];
			}

			if($item['item_id']==$item_id)
			{
				$itemalreadyinsale=TRUE;
				$updatekey=$item['line'];
			}
		}

		$insertkey=$maxkey+1;
		$item_info=$this->CI->Item->get_info($item_id);
		//array/cart records are identified by $insertkey and item_id is just another field.
		$item = array(($insertkey)=>
		array(
			'item_id'=>$item_id,
			'line'=>$insertkey,
			'name'=>$item_info->name,
			'item_number'=>$item_info->item_number,
			'quantity'=>$quantity,
			'stock'=>$item_info->quantity,
			'price'=>$item_info->unit_price
			)
		);

		//Item already exists and is not serialized, add to quantity
		if($itemalreadyinsale)
		{
			if ($items[$updatekey]['quantity']+1 <= $items[$updatekey]['stock']) {
				$items[$updatekey]['quantity']+=$quantity;
			} else {
				return false;
			}
		}
		else
		{
			//add to existing array
			$items+=$item;
		}

		$this->set_cart($items);
		return true;

	}
	
	function out_of_stock($item_id)
	{
		//make sure item exists
		if($this->validate_item($item_id) == false)
        {
            return false;
        }

		//$item = $this->CI->Item->get_info($item_id);
		$item_quantity = $this->CI->Item->get_info($item_id)->quantity; 
		$quanity_added = $this->get_quantity_already_added($item_id);
		
		if ($quanity_added > $item_quantity)
		{
			return true;
		}
		
		return false;
	}
	
	function get_quantity_already_added($item_id)
	{
		$items = $this->get_cart();
		$quanity_already_added = 0;
		foreach ($items as $item)
		{
			if($item['item_id']==$item_id)
			{
				$quanity_already_added+=$item['quantity'];
			}
		}
		
		return $quanity_already_added;
	}
	
	function get_item_id($line_to_get)
	{
		$items = $this->get_cart();

		foreach ($items as $line=>$item)
		{
			if($line==$line_to_get)
			{
				return $item['item_id'];
			}
		}
		
		return -1;
	}

	function edit_item($line,$quantity,$price)
	{
		$items = $this->get_cart();
		if(isset($items[$line]))
		{
			$items[$line]['quantity'] = $quantity;
			$items[$line]['price'] = $price;
			$this->set_cart($items);
		}

		return false;
	}

	function is_valid_receipt($receipt_sale_id)
	{
		//POS #
		$pieces = explode($receipt_sale_id);

		if(count($pieces)==1)
		{
			return $this->CI->Sale->exists($pieces[0]);
		}

		return false;
	}

	function copy_entire_sale($sale_id)
	{
		$this->empty_cart();
		$this->remove_customer();

		foreach($this->CI->Sale->get_sale_items($sale_id)->result() as $row)
		{
			$this->add_item($row->item_id,$row->quantity_purchased,$row->item_unit_price);
		}
		foreach($this->CI->Sale->get_sale_payments($sale_id)->result() as $row)
		{
			$this->add_payment_copy($row->payment_type,$row->payment_amount);
		}
		$this->set_customer($this->CI->Sale->get_customer($sale_id)->person_id);

	}

	function delete_item($line)
	{
		$items=$this->get_cart();
		unset($items[$line]);
		$this->set_cart($items);
	}

	function empty_cart()
	{
		$this->CI->session->unset_userdata('cart');
	}

	function remove_customer()
	{
		$this->CI->session->unset_userdata('customer');
	}

	function clear_mode()
	{
		$this->CI->session->unset_userdata('sale_mode');
	}

	function clear_all()
	{
		$this->clear_mode();
		$this->empty_cart();
		$this->empty_payments();
		$this->remove_customer();
	}

	function get_total()
	{
		$total = 0;
		foreach($this->get_cart() as $item)
		{
            $total += ( $item['price'] * $item['quantity'] );
		}

		return $total;
	}
    
    function validate_item(&$item_id)
    {
        //make sure item exists
        if(!$this->CI->Item->exists($item_id))
        {
            //try to get item id given an item_number
            $item_id = $this->CI->Item->get_item_id($item_id);

            if(!$item_id)
                return false;
        }
        return true;
    }
    
    function validate_customer(&$customer_id)
    {
    	//make sure item exists
    	if(!$this->CI->Customer->exists($customer_id))
    	{
    		//try to get item id given an item_number
    		$customer_id = $this->CI->Customer->get_customer_id($customer_id);
    
    		if(!$customer_id)
    			return false;
    	}
    	return true;
    }
}
?>